import smtplib
from email.mime.text import MIMEText
from email.header import Header
import random
import string
from datetime import datetime, timedelta
import sys
import os

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config import SMTP_SERVER, SMTP_PORT, SENDER_EMAIL, SENDER_PASSWORD, validate_config

def generate_verification_code(length=6):
    """生成指定长度的数字验证码"""
    return ''.join(random.choices(string.digits, k=length))

def send_verification_email(receiver_email, verification_code):
    """发送验证码邮件（支持SSL加密）"""
    try:
        # 验证配置参数有效性
        if not all([SMTP_SERVER, SMTP_PORT, SENDER_EMAIL, SENDER_PASSWORD]):
            raise ValueError("邮件服务器配置不完整")

        # 创建邮件内容（包含HTML格式备选）
        subject = "PKU二手交易平台 - 邮箱验证码"
        text_content = f"""
        您好！

        您的验证码是：{verification_code}

        此验证码将在10分钟内有效。
        如果这不是您的操作，请忽略此邮件。

        ---------------------
        PKU二手交易平台团队
        """

        html_content = f"""
        <html>
          <body>
            <p>您好！</p>
            <p>您的验证码是：<strong>{verification_code}</strong></p>
            <p style="color: #666;">此验证码将在10分钟内有效。<br/>
            如果这不是您的操作，请忽略此邮件。</p>
            <hr/>
            <p style="color: #999;">PKU二手交易平台团队</p>
          </body>
        </html>
        """

        # 创建多部分邮件对象
        from email.mime.multipart import MIMEMultipart
        msg = MIMEMultipart('alternative')  # 允许内容替代版本
        msg.attach(MIMEText(text_content, 'plain', 'utf-8'))
        msg.attach(MIMEText(html_content, 'html', 'utf-8'))
        # msg = MIMEText(text_content, 'plain', 'utf-8')
        # html_part = MIMEText(html_content, 'html', 'utf-8')
        # msg.attach(html_part)

        msg['Subject'] = Header(subject, 'utf-8')
        msg['From'] = f"PKU二手交易平台 <{SENDER_EMAIL}>"  # 增加发件人名称
        msg['To'] = receiver_email

        # 使用SSL加密连接
        with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server:
            server.login(SENDER_EMAIL, SENDER_PASSWORD)
            server.sendmail(SENDER_EMAIL, [receiver_email], msg.as_string())
            
        return True
    except smtplib.SMTPException as e:
        print(f"SMTP协议错误: {e}")
        return False
    except Exception as e:
        print(f"系统错误: {str(e)}")
        return False

def send_verification_code(db, email):
    """生成并发送验证码，同时保存到数据库"""
    try:
        # 生成验证码
        code = generate_verification_code()
        
        # 设置验证码过期时间（10分钟后）
        expired_at = (datetime.now() + timedelta(minutes=10)).strftime('%Y-%m-%d %H:%M:%S')
        
        # 发送验证码邮件
        if send_verification_email(email, code):
            # 将验证码保存到数据库
            from func.user_service import add_verification_code
            code_id = add_verification_code(db, email, code, expired_at)
            return code_id
        else:
            raise Exception("发送验证码邮件失败")
    except Exception as e:
        raise Exception(f"发送验证码失败: {str(e)}")

def verify_code(db, email, code):
    """验证用户输入的验证码"""
    try:
        from func.user_service import get_verification_code, delete_verification_code
        
        # 获取存储的验证码
        stored_code = get_verification_code(db, email)
        
        if not stored_code:
            raise Exception("验证码不存在或已过期")
        
        # 检查验证码是否过期
        expired_at = datetime.strptime(stored_code['expired_at'], '%Y-%m-%d %H:%M:%S')
        if datetime.now() > expired_at:
            # 删除过期的验证码
            delete_verification_code(db, email)
            raise Exception("验证码已过期")
        
        # 验证码匹配
        if stored_code['code'] == code:
            # 验证成功后删除验证码
            delete_verification_code(db, email)
            return True
        else:
            raise Exception("验证码错误")
            
    except Exception as e:
        raise Exception(f"验证码验证失败: {str(e)}") 